const Koa = require('koa')
const path = require('path')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const {
  koaSwagger
} = require('koa2-swagger-ui')
const koaStatic = require("koa-static")
const {
  koaBody
} = require('koa-body')
const routerHandle = require("./startHandle/routes")
const JwtHandle = require("./startHandle/jwt")
const resultMiddle = require('./middle/result-middle')
const userMiddle = require('./middle/user-middle')
const cors = require('koa2-cors');
app.use(koaStatic(path.join(__dirname, "public")))
app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, "public", "resource", "uploads"),
    keepExtensions: true
  }
}))
//跨域
app.use(cors());
//JSON统一响应工具
app.use(resultMiddle)
// 异常处理器
app.use(async (ctx, next) => {
  await next().catch((err) => {
    ctx.result.error(err.message, err.status)
  })
})
// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.use(
  koaSwagger({
    routePrefix: '/swagger', // host at /swagger instead of default /docs
    swaggerOptions: {
      url: 'http://localhost:3000/doc/swagger.json', // example path to json
    },
  }),
);
// JWT启动器
JwtHandle(app)
// 获取用户信息
app.use(userMiddle)
//路由启动器
routerHandle(app)

module.exports = app